package top.hepingan.java.controller.yonghu;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.hepingan.java.common.Result;
import top.hepingan.java.entity.Dish;
import top.hepingan.java.entity.Review;
import top.hepingan.java.mapper.DishMapper;
import top.hepingan.java.mapper.ReviewMapper;
import top.hepingan.java.service.DishService;
import top.hepingan.java.utils.UserUtils;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@RequestMapping("/user")
@RestController
@Slf4j
@RequiredArgsConstructor
public class DishShow {
    @Autowired
    private DishMapper dishMapper;
    /**
     * 菜品展示 时间
     */
    @RequestMapping("/dishShow")
    public Result dishShow( @RequestParam(required = false) String date){
        if (date != null && !date.isEmpty()) {
            // 解析日期
            LocalDate localDate = LocalDate.parse(date);

            // 创建该日期的开始和结束时间
            LocalDateTime startOfDay = localDate.atStartOfDay();
            LocalDateTime endOfDay = localDate.atTime(23, 59, 59);

            // 使用大于等于开始时间且小于等于结束时间的条件
            LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.ge(Dish::getCreatedTime, startOfDay)
                    .le(Dish::getCreatedTime, endOfDay);

            return Result.ok().setData(dishMapper.selectList(queryWrapper));
        }

        return null;
    }
//    获取菜品详情的接口

//    获取菜品评论的接口
    /**
     * 传递菜品id
     */
    @Autowired
    private ReviewMapper reviewMapper;
    @RequestMapping("/dishDetail/{id}")
    public Result dishDetail(@PathVariable Integer id){
        LambdaQueryWrapper<Review> lq=new  LambdaQueryWrapper<>();
        lq.eq(Review::getDishId,id);
        List<Review> review = reviewMapper.selectList(lq);
        return Result.ok().setData(review);
    }

//    提交用户评论的接口
    @PostMapping("/dishReview")
    public Result dishReview(@RequestBody Review review){

        //重复评价判断-根据菜品ID+用户ID
        Integer userId =   UserUtils.getCurrentLoginId();
        LambdaQueryWrapper<Review> lq=new  LambdaQueryWrapper<>();
        lq.eq(Review::getDishId,review.getDishId())
        .eq(Review::getUserId,userId);
        if(!reviewMapper.selectList(lq).isEmpty()){
            return Result.error("您已经评价过该菜品了");
        }


        review.setCreatedTime(LocalDateTime.now());
        ///

        review.setUserId( userId.longValue());
        reviewMapper.insert(review);
        return Result.ok();
    }
}
